<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>随心——聊天室</title>
    <link rel="stylesheet" href="/stylesheets/css/index.css">
  </head>
  <body>
    <div class="container">
      <%- include('he_nav') -%>

      <div class="main box">
        <div class="postedchatmes">
          <!-- <button type="submit" name="button" style="margin-left: 92%">留言记录</button> -->
        </div>

        <form action="/users/chatroom" method="post">
          <textarea name="content" maxlength="100" placeholder="请输入聊天内容（100字以内）"></textarea>
          <button type="submit" name="button">发送</button>
        </form>
      </div>

      <%- include('sid_footer') -%>
    </div>
    <script type="text/javascript" src="../../../javascripts/open.js"></script>
    <script type="text/javascript" src="/socket.io/socket.io.js"></script>
    <script type="text/javascript">
       const socket = io.connect();
       const listdom = document.querySelector(".postedchatmes");
       const form = document.querySelector("form");
       const navlogname = "<%=user.loginname%>";

       socket.emit("enter", "欢迎"+navlogname+"进入聊天室。");

       socket.on("reply", str=>{
         const pdom = document.createElement("p");
         pdom.innerText = str;
         listdom.appendChild(pdom);
       });

       form.onsubmit = async function (event) {
         event.preventDefault();
         const content = form.querySelector("textarea").value;
         if (content) {                     //聊天内容不能为空
           socket.emit("send", content);
           await fetch("/users/chatroom",{
               method:"POST",
               body: JSON.stringify({content}),
               credentials:"include",
               headers:{
                 "Content-Type":"application/json"
               }
             }).then(res=>res.text())
             .catch(e => console.log("error", e));
         }
       }

       socket.on("load",doc=>{
         var {
           id,
           loginname,
           content,
           createTime,
           S_Time
         } = doc;
         content = content.replace(/\r\n/g, '</p><p>').replace(/\n/g, '</p><p>').replace(/\s/g, '&nbsp');
         const mesCell = document.createElement("div");
         mesCell.innerHTML = `
                <div><p>${content}</p></div>
                <p>${loginname}--${S_Time}</p>
                `;
         if (loginname === navlogname) {
           mesCell.setAttribute("style","padding-left:30%;");
         }
         listdom.appendChild(mesCell);
         mesCell.scrollIntoView();
         console.log("listdom=",listdom);
       });
     </script>

  </body>
</html>
